package com.yuhanginfo.common.web;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ckfinder.connector.configuration.Configuration;
import com.ckfinder.connector.data.AccessControlLevel;
import com.ckfinder.connector.utils.AccessControlUtil;
import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.exception.YuHangInfoRuntimeException;
import com.yuhanginfo.common.utils.FileUtils;
import com.yuhanginfo.modules.web.security.AdminRealm.Principal;
import com.yuhanginfo.modules.web.util.WebUserUtils;

/**
 * CKFinder配置
 * @author YuHangInfo
 * @version 2014-06-25
 */
public class CKFinderConfig extends Configuration {
	private static Logger logger = LoggerFactory.getLogger(CKFinderConfig.class);
	public CKFinderConfig(ServletConfig servletConfig) {
        super(servletConfig);  
    }
	
	@Override
    protected Configuration createConfigurationInstance() {
		Principal principal = (Principal) WebUserUtils.getAdminPrincipal();
		if (principal == null){
			return new CKFinderConfig(this.servletConf);
		}
		boolean isView = true;
		boolean isUpload = true;
		boolean isEdit = true;
		AccessControlLevel alc = this.getAccessConrolLevels().get(0);
		alc.setFolderView(isView);
		alc.setFolderCreate(isEdit);
		alc.setFolderRename(isEdit);
		alc.setFolderDelete(isEdit);
		alc.setFileView(isView);
		alc.setFileUpload(isUpload);
		alc.setFileRename(isEdit);
		alc.setFileDelete(isEdit);
		AccessControlUtil.getInstance(this).loadACLConfig();
		try {
			this.baseURL = FileUtils.path(Servlets.getRequest().getContextPath() + Global.USERFILES_BASE_URL + principal + "/");
			this.baseDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + principal + "/");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new YuHangInfoRuntimeException(e.getMessage());
		}
		return new CKFinderConfig(this.servletConf);
    }

    @Override  
    public boolean checkAuthentication(final HttpServletRequest request) {
        return WebUserUtils.getAdminPrincipal()!=null;
    }

}
